import isEmpty from 'lodash/isEmpty';
import {Button, Form, Menu, Dropdown, Icon, Tag, Modal} from 'antd';
import {WeaSearchGroup, WeaDropdown,WeaTag, WeaFormItem} from 'ecCom';
import {WeaSwitch} from 'comsMobx';
import {toJS} from 'mobx';
// import CoworkConstant from './CoworkConstant';
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

export const getNewFiels = (fields = {}) => {
  let params = {};
  if (!isEmpty(fields)) {
    for (let key in fields) {
      params[fields[key].name] = fields[key].value
    }
  }
  return params
}

//用于获取高级搜索中的表单控件
//一定要先初始化initFormFields表单对象
//用于获取高级搜索中的表单控件
export const getSearchs = (form, datas) => {
  const {isFormInit} = form;
  let group = [];
  const formParams = form.getFormParams();
  isFormInit && datas && datas.map((c,ecindex) =>{
    let items = [];
    c.items.map(fields => {
      const domKey = typeof fields.domkey === "object" ? fields.domkey[0] : fields.domkey;
      items.push({
        com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@pbvv3p@${domKey}`}
          label={`${fields.label}`}
          labelCol={{span: `${fields.labelcol}`}}
          wrapperCol={{span: `${fields.fieldcol}`}}>
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@nioprs@${domKey}`} fieldConfig={fields} form={form} formParams={formParams}/>
        </WeaFormItem>),
        colSpan:1
      })
    });
    group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@tcq3ip@${ecindex}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
  });
  return group;
}

// 打开查看某个协作的页面
export const getViewCoworkUrl = (coworkId) => {
	let url = "/spa/cowork/static/index.html#/cowork/" + coworkId;
	return url;
}

// 打开查看某个协作具体楼层的页面
export const getViewCoworkOfFloorNnmUrl = (coworkId, floorNum) => {
	let url = "/spa/cowork/static/index.html#/cowork/" + coworkId + "/" + floorNum;
	return url;
}

export const createReplyBottomAtt = (label, list, href, key) => {
  if (!list || list.length == 0) return null;
  return (
    <div className="cowork-att-list">
      <div className="cowork-att-content" >
        {key === "doc" && <div className="icon-search-File content-icon"></div>}
        {key === "wf" && <div className="icon-coms-Workflow-o content-icon"></div>}
        {key === "crm" && <div className="icon-coms-currency-Customer content-icon"></div>}
        {key === "project" && <div className="icon-coms-task-list content-icon"></div>}
        {key === "task" && <div className="icon-coms-currency-Task content-icon"></div>}
        {key === "acc" && <div className="icon-coms-currency-Enclosure content-icon"></div>}
        {/* <div className="cowork-att-label">{label}</div> */}
        <ul>
          {list.map((item, index) => {
            if(key !== "acc") {
              return (
                <li><a href={item.url} target="_blank">{item.name}</a></li>
              );
            } else {
                return (
                    <li className="workflow-accessory">
                      <div className="workflow-accessory-item">
                        <a className="item-a" onClick={() => window.open(item.url)} title={item.name}>{item.name}</a>
                        <i className="icon-coms-download" onClick={(e) => {
                          e.stopPropagation();
                          window.open(item.downUrl);
                        }}></i>
                        <span>{item.downName}</span>
                      </div>
                  </li>
                );
            }
          })}
        </ul>
      </div>
    </div>
  );
}
export const dateFormat = (date, fmt = 'yyyy-MM-dd') => {
  if (date && fmt) {
    let _this = date
    const type = Object.prototype.toString.call(date)
    if (type == "[object String]") {
      let dateArray = date.split(" "),
        d1 = dateArray[0].split("-"),
        d2 = dateArray[1] ? dateArray[1].split(":") : [];
      _this = new Date((d1[0] || 0) * 1, (d1[1] || 0) * 1 - 1, (d1[2] || 0) * 1, (d2[0] || 0 ) * 1, (d2[1] || 0) * 1, (d2[2] || 0) * 1)
    } else if (type == "[object Date]") {
      
    } else {
      return ""
    }
    let o = {
      "M+": _this.getMonth() + 1, //月份
      "d+": _this.getDate(), //日
      "h+": _this.getHours() % 12 == 0 ? 12 : _this.getHours() % 12, //小时
      "H+": _this.getHours(), //小时
      "m+": _this.getMinutes(), //分
      "s+": _this.getSeconds(), //秒
      "q+": Math.floor((_this.getMonth() + 3) / 3), //季度
      "S": _this.getMilliseconds() //毫秒
    };
    let week = {
      "0": "\\u65e5",
      "1": "\\u4e00",
      "2": "\\u4e8c",
      "3": "\\u4e09",
      "4": "\\u56db",
      "5": "\\u4e94",
      "6": "\\u516d"
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
      let weekStr = ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\\u661f\\u671f" : "\\u5468") : "") + week[_this.getDay() + ""]
      fmt = fmt.replace(RegExp.$1, Utils.GB2312UnicodeConverter.ToGB2312(weekStr));
    }
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  } else {
    return ""
  }
}

export const imgZoom = (dom, parentSelector) => {
  let imgList = jQuery(parentSelector + " img",dom);
  // const { handwriting_download_switch = 0 } = WfForm.getLayoutStore().propFileCfg;
  imgList.each((index,img) => {
    let $img = $(img);
    // if($img.attr("name") == "handWrittenSign" && handwriting_download_switch == 1)
      // return;
    if ($img.attr("resize")) {
      return;
    }
    if ($img.parents(".ui-coomixPic").length > 0) {
      return;
    }
    $img.css({"max-width": "400px", "max-height" : "400px"}).attr("resize", 1).coomixPic({
      path:'/blog/js/weaverImgZoom/images',
      preload:true,
      blur: true,
      left: getLabel(26921, '向左转'),
      right: getLabel(26922, '向右转'),
      source: getLabel(26923, '查看原图'),
      hide: getLabel(26985, '收起')
    });
  });
};

export const createAttachLi = (item) => {
  return (
    <li className="cowork-accessory-item" >
      {/* {item.docextendname && item.docextendname == 'html' && <em className="icon-coms-html2"></em>}
      {item.docextendname && item.docextendname == 'doc' && <em className="icon-coms-word2"></em>}
      {item.docextendname && item.docextendname == 'docx' && <em className="icon-coms-word2"></em>}
      {item.docextendname && item.docextendname == 'wps' && <em className="icon-coms-word2"></em>}
      {item.docextendname && item.docextendname == 'jpeg' && <em className="icon-coms-pic2"></em>}
      {item.docextendname && item.docextendname == 'png' && <em className="icon-coms-pic2"></em>}
      {item.docextendname && item.docextendname == 'jpg' && <em className="icon-coms-pic2"></em>}
      {item.docextendname && item.docextendname == 'xlsx' && <em className="icon-coms-currency2"></em>}
      {item.docextendname && item.docextendname == 'xls' && <em className="icon-coms-currency2"></em>}
      {item.docextendname && item.docextendname == 'zip' && <em className="icon-coms-rar2"></em>}
      {item.docextendname && item.docextendname == 'excel' && <em className="icon-coms-excel2"></em>}
      {item.docextendname && item.docextendname == 'pdf' && <em className="icon-coms-pdf2"></em>}
      {item.docextendname && item.docextendname == 'ppt' && <em className="icon-coms-ppt2"></em>} */}
      <a className="item-a" onClick={() => window.open(item.url)} title={item.name}>{item.name}</a>
      <i className="icon-coms-download" onClick={(e) => {
        e.stopPropagation();
        window.open(item.downUrl);
      }}></i>
      <span>{item.downName}</span>
    </li>
  );
};

//灰度算法
export const isColorDark = (colorHex, threshold) => {
  if(!colorHex || typeof colorHex != 'string')
  return false;
  if(colorHex.indexOf('#') == 0) {
    colorHex = colorHex.substring(1, colorHex.length);
  }
  var temp = colorHex.split('');
  var R,G,B;
  // #abcdef
  if(temp.length == 6){
    R = temp[0]+temp[1];
    G = temp[2]+temp[3];
    B = temp[4]+temp[5];
    
  }
  // #abc
  else if(temp.length == 3){
    R = temp[0]+temp[0];
    G = temp[1]+temp[1];
    B = temp[2]+temp[2];
  }
  else {
    return false;
  }
  var Gray = parseInt(R,16) *0.299 + parseInt(G,16) * 0.587 + parseInt(B,16) * 0.114;
  if(Gray < (threshold?threshold:125)){
    return true;
  }else{
    return false;
  }
}

export const createMarkMenu = (labelList, onMark) => {
  return (
    <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@t82vdn`} className="wea-cowork-dropdown-menu" onClick={onMark}>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@b0poxj`} key="read">{getLabel(25425, '已读')}</Menu.Item>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@mjxa2f`} key="unread">{getLabel(83697, '未读')}</Menu.Item>
      <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@y8x44a`}/>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@1vy0l4`} key="important">{getLabel(382626, '标星')}</Menu.Item>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@8j4ron`} key="normal">{getLabel(382669, '取消标星')}</Menu.Item>
      <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@0qy6io`}/>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@sdn5rg`} key="hidden">{getLabel(16636, '隐藏')}</Menu.Item>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@eyx635`} key="show">{getLabel(25424, '取消隐藏')}</Menu.Item>
      <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@pgiins`}/>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@zuc2a6`} key="tag">
        {getLabel(176, '标签')}...
        <span className="icon-coms-Flow-setting"/>
      </Menu.Item>
      {labelList.length > 0 && labelList.filter((label) => label.labelType != 'typePlate').map((label,ecindex)=> {
        return (
        <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@oq5war@${ecindex}`} key={label.id} className="wea-cowork-tag-menu-item">
          <WeaTag ecId={`${this && this.props && this.props.ecId || ''}_WeaTag@xbinmg@${ecindex}`} 
            className="setable-label"
            color={label.labelColor}
            >
            {label.labelName}
          </WeaTag>
        </Menu.Item>
      )})}
      <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@rwygvd`}/>
      <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@5h4az1`} key="deleteAll">{getLabel(31219, '取消所有标签')}</Menu.Item>
    </Menu>
  );
}

// export const createSortMenu = (sortKey, onSort) => {
//   return (
//     <WeaDropdown datas={CoworkConstant.sortMenu} onSelect={onSort} currentKey={sortKey} />
//   );
// }

export const onCheck = (form, func) => {
  form.validateForm().then(f=>{
    if(f.isValid){
      func && typeof func == 'function' && func();
    }else{
      f.showErrors();
    }
  });
}

//信息确认
export const doConfirm = (content, func) => {//确认信息， 方法， 方法参数
  Modal.confirm({
    title: `${getLabel(131329,'信息确认')}`,
    content: content,
    okText: `${getLabel(382958,'确定')}`,
    cancelText:`${getLabel(31129,'取消')}`,
    onOk: () => func && func(),
  })
}
